<template>
	<view>
		<view class="order-page" @touchmove.prevent v-if="isShow">
			<!-- 订单类型切换 -->
			<view class="order-type-switch" :style="{marginTop: statusBarHeight + 'px'}">
				<text class="order-type" :class="{ active: submitType == 0 }" @click="switchOrderType(0)">全部订单</text>
				<text>⇆</text>
				<text class="order-type" :class="{ active: submitType == 2 }" @click="switchOrderType(2)">批量订单</text>
			</view>

			<!-- Tab 栏 -->
			<view class="tabs">
				<view class="tab" :class="{ active: status === 0 }" @click="changeTab(0)">全部</view>
				<view class="tab" :class="{ active: status === 2 }" @click="changeTab(2)" v-if="submitType == 0">处理中
				</view>
				<view class="tab" :class="{ active: status === 1 }" @click="changeTab(1)" v-if="submitType == 0">成功
				</view>
				<view class="tab" :class="{ active: status === 3 }" @click="changeTab(3)" v-if="submitType == 0">失败
				</view>

				<view class="tab" :class="{ active: status === 1 }" @click="changeTab(1)" v-if="submitType != 0">处理中
				</view>
				<view class="tab" :class="{ active: status === 2 }" @click="changeTab(2)" v-if="submitType != 0">已完成
				</view>
			</view>

			<!-- 订单列表 -->
			<scroll-view scroll-y enable-back-to-top @scrolltolower="loadMore" @refresherrefresh="onRefresh"
				refresher-enabled :refresher-triggered="isRefreshing" style="height: 75%; padding-top: 24rpx;"
				v-if="submitType == 0">
				<block v-for="(item, index) in orders" :key="index">
					<view class="order-item" @click="toSigleOrderDetail(item)">
						<view class="order-item-title">
							<view class="order-item-title-left">
								<text class="order-item-title-text">卡号：{{ item.cardNum ? item.cardNum : '-'}}</text>
								<image src="/static/images/ic_copy.png" style="height: 24rpx; width: 24rpx;"
									@click.stop="$app.toCopy(item.cardNum)"></image>
							</view>
							<view class="order-status"
								:style="{ color: `${getStatusColor(item.status)}`, border: `2rpx solid ${getStatusColor(item.status)}`, backgroundColor: `${getStatusBgColor(item.status)}` }">
								{{ getStatusName(item.status) }}
							</view>
						</view>

						<view class="order-item-content">
							<image class="order-item-content-image" mode="aspectFit" :src="item.mImg"></image>
							<view class="order-item-content-right">
								<view class="order-item-content-title">{{item.prodName}}</view>
								<view class="order-item-content-time">提交时间：{{ item.submitTime }}</view>
							</view>
						</view>

						<view class="order-item-result">
							<view>
								<view>
									{{ getResultStatus(item.settStatus)}}
								</view>
								<view style="margin-top: 4rpx;" v-if="item.settStatus == '1'">
									{{ item.handleTime}}
								</view>
							</view>
							<view class="order-info">实际可得：<text
									style="font-weight: 700;">{{ item.amount ? '￥'+item.amount : '-' }}</text></view>
						</view>
					</view>
				</block>
				<view v-if="loadingMore" class="loading-more">加载中...</view>
				<view v-if="noMoreData" class="no-more-data">已经全部加载完毕</view>
			</scroll-view>

			<!-- 批量订单列表 -->
			<scroll-view scroll-y enable-back-to-top @scrolltolower="loadMore" @refresherrefresh="onRefresh"
				refresher-enabled :refresher-triggered="isRefreshing" style="height: 75%; padding-top: 24rpx;" v-else>
				<block v-for="(item, gIndex) in orders" :key="gIndex">
					<view class="order-item" @click="toOrderDetail(item)">
						<view class="order-item-title">
							<view class="order-item-title-left">
								<text class="order-item-title-text">订单号：{{ item.batchNo ? item.batchNo : '-'}}</text>
								<image src="/static/images/ic_copy.png" style="height: 24rpx; width: 24rpx;"
									@click.stop="toCopy(item.batchNo)"></image>
							</view>
							<view class="order-status"
								:style="{ color: `${getFetchStatusColor(item.handleStatus)}`, border: `2rpx solid ${getFetchStatusColor(item.handleStatus)}`, backgroundColor: `${getFetchStatusBgColor(item.handleStatus)}` }">
								{{ getFetchStatusName(item.handleStatus) }}
							</view>
						</view>

						<view class="order-item-content">
							<image class="order-item-content-image" mode="aspectFit" :src="item.mImg"></image>
							<view class="order-item-content-right">
								<view class="order-item-content-title">{{item.prodName}}
									<text
										style="margin-left: 5rpx; padding: 2rpx 10rpx; font-size: 20rpx; border: #4D7EF4 solid 2rpx; color: #4D7EF4; border-radius: 8rpx;">{{item.totalNum}}张</text>
								</view>

								<view class="order-item-content-info">
									总面值:{{item.totalFaceValue}}元
								</view>
								<view class="order-item-content-info">
									处理中 {{item.totalNum - item.succNum - item.failNum}} | 成功 {{item.succNum}} | 失败
									{{item.failNum}}
								</view>
								<view class="order-item-content-time">提交时间：{{ item.createTime }}</view>
							</view>
						</view>

						<view class="order-item-some-result">
							<view class="order-info">实际可得：<text
									style="font-weight: 700;">{{ item.totalAmount ? '￥'+item.totalAmount : '-' }}</text>
							</view>

							<view class="order-info" style="margin-left: 40rpx;">已结算：<text
									style="font-weight: 700;">{{ item.mercSettAmt ? '￥'+item.mercSettAmt : '-' }}</text>
							</view>
						</view>
					</view>
				</block>
				<view v-if="loadingMore" class="loading-more">加载中...</view>
				<view v-if="noMoreData" class="no-more-data">已经全部加载完毕</view>
			</scroll-view>


			<custom-tabbar value="order"></custom-tabbar>
		</view>
    <view v-else>
      <custom-header title="报价" :isHaveBack="false"></custom-header>
      <scroll-view scroll-x class="card-scroll-container" show-scrollbar="false">
        <view v-for="(item, index) in typeList" :key="index"
              :class="['type-item', selectedIndex === index ? 'active' : '']" @click="switchCardType(index)">
          {{ item.name }}
        </view>
      </scroll-view>
      <block v-for="(item, index) in cardList" :key="index">
        <view style="display: flex; justify-content: space-between; padding: 20rpx 40rpx;" @click="toCardList(item)">
          <view style="display: flex; align-items: center;">
            <image style="width: 120rpx; height: 120rpx;" :src="item.mimg" mode="aspectFit"></image>
            <view style="color: black; font-size: 28rpx; margin-left: 20rpx;">{{ item.name }}</view>
          </view>

          <view style="display: flex; align-items: center;">
            <text style="font-size: 22rpx;">报价</text>
            <image src="../../static/images/arrow_right.png"
                   style="width: 15rpx; height: 27rpx; margin-left: 10rpx;"></image>
          </view>
        </view>
        <view style="height: 2rpx; width: 100%; background-color: rgba(0, 0, 0, 0.09);"></view>
      </block>
      <custom-tabbar value="order"></custom-tabbar>
    </view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				submitType: 0, // 全部订单或批量订单 0全部 2批量
				status: 0, // 当前标签 0全部 1处理中 2成功 3失败
				orders: [],
				loadingMore: false, //加载中
				noMoreData: false, //没有更多
				page: 1,
				pageSize: 10,
				isRefreshing: false, //正在刷新
				total: 0, //总数据量
				isEnd: false, // 是否全部加载完成
				rightSafeArea: 0,
				statusBarHeight: 20,
				imgHost: '',
				touchmoveHandler: null, // 添加一个变量来存储事件处理函数引用
				isShow: uni.getStorageSync("isShow"),
        typeList: [], //类型列表（审核data）
        cardList: [], //卡片列表
        selectedIndex: 0, //类型下标
        typeId: null, //当前类型
			};
		},
		async onShow() {
			console.log("初始化下标", this.submitType)
			const params = uni.getStorageSync('navTabIndex');
			if (params !== null && params !== undefined && params !== '') {
				console.log('Received params:', params);
				this.switchOrderType(params);
				// 清除本地存储中的参数，避免重复使用
				uni.removeStorageSync('navTabIndex');
			} else {
				if (this.submitType == 0) {
					this.fetchOrders(0);
				} else {
					this.fetchBatchOrders(0)
				}
			}
			const res = await this.$http({
				method: 'GET',
				url: '/user/base/info',
			});
			if (res) {
				const user = res.data;
				this.$app.setUserInfo(user);
			}

      if (!this.isShow){
        this.getTypeList();
      }
		},
		created() {
			// 获取系统信息
			const systemInfo = uni.getSystemInfoSync()
			//获取状态栏高度
			this.statusBarHeight = systemInfo.statusBarHeight
			console.log("高度", this.statusBarHeight)
			// 微信小程序适配
			// #ifdef MP-WEIXIN
			const menuRect = uni.getMenuButtonBoundingClientRect()
			this.rightSafeArea = systemInfo.windowWidth - menuRect.left // 计算右侧避让距离[6](@ref)
			// #endif

			this.imgHost = this.$app.imgApiHost;
		},
		mounted() {
			this.touchmoveHandler = (e) => {
				if (!e.target.closest('.scroll-view')) {
					e.preventDefault();
				}
			};

			const orderPage = document.querySelector('.order-page');
			if (orderPage) {
				orderPage.addEventListener('touchmove', this.touchmoveHandler, {
					passive: false
				});
			}
		},
		beforeDestroy() {
			// 移除事件监听
			const orderPage = document.querySelector('.order-page');
			if (orderPage && this.touchmoveHandler) {
				orderPage.removeEventListener('touchmove', this.touchmoveHandler);
			}

			// 清除引用
			this.touchmoveHandler = null;
		},
		methods: {
			switchOrderType(type) {
				this.submitType = type;
				this.status = 0;

				this.changeTab(0)
			},
			changeTab(tab) {
				this.status = tab;

				this.onRefresh();
			},
			onRefresh() {
				this.isRefreshing = true;
				this.resetPagination();

				if (this.submitType == 0) {
					this.fetchOrders(1);
				} else {
					this.fetchBatchOrders(1)
				}
			},
			// 清空状态
			resetPagination() {
				this.page = 1;
				this.total = 0;
				this.orders = [];
				this.loadingMore = false;
				this.noMoreData = false;
			},
			loadMore() {
				if (!this.loadingMore && !this.noMoreData) {
					this.loadingMore = true;

					if (this.submitType == 0) {
						this.fetchOrders(2)
					} else {
						this.fetchBatchOrders(2)
					}
				}
			},
			// 请求订单数据 states 0=初始化 1=刷新 2=加载
			async fetchOrders(states) {
				const res = await this.$http({
					method: 'POST',
					url: `/order/list?pageNum=${this.page}&pageSize=${this.pageSize}`,
					data: {
						pageSize: this.pageSize,
						pageNum: this.page,
						submitType: this.submitType == 0 ? '' : this.submitType,
						status: this.status == 0 ? '' : this.status
					}
				});

				if (res) {
					//状态修改
					if (states == 1) {
						this.isRefreshing = false
					} else if (states == 2) {
						this.loadingMore = false;
					}

					// 首次加载
					if (this.page === 1) {
						this.orders = res.rows
						this.total = res.total
					} else {
						// 追加数据
						this.orders = [...this.orders, ...res.rows]
					}

					// 判断是否加载完成
					this.isEnd = (this.page * this.pageSize) >= res.total

					// 翻页或加载到最后了
					if (!this.isEnd) {
						this.page++;
					} else {
						this.noMoreData = true;
					}
				} else {
					if (states == 1) {
						this.isRefreshing = false
					} else if (states == 2) {
						this.loadingMore = false;
					}
				}
			},
			// 请求批量订单数据 states 0=初始化 1=刷新 2=加载
			async fetchBatchOrders(states) {
				const res = await this.$http({
					method: 'POST',
					url: `/order/batch/list?pageNum=${this.page}&pageSize=${this.pageSize}`,
					data: {
						handleStatus: this.status == 0 ? '' : this.status
					}
				});

				if (res) {
					//状态修改
					if (states == 1) {
						this.isRefreshing = false
					} else if (states == 2) {
						this.loadingMore = false;
					}

					// 首次加载
					if (this.page === 1) {
						this.orders = res.rows
						this.total = res.total
					} else {
						// 追加数据
						this.orders = [...this.orders, ...res.rows]
					}

					// 判断是否加载完成
					this.isEnd = (this.page * this.pageSize) >= res.total

					// 翻页或加载到最后了
					if (!this.isEnd) {
						this.page++;
					} else {
						this.noMoreData = true;
					}
				} else {
					if (states == 1) {
						this.isRefreshing = false
					} else if (states == 2) {
						this.loadingMore = false;
					}
				}
			},
			getStatusColor(status) {
				if (status == 1) return '#6AE8BD';
				if (status == 2) return '#FC926A';
				if (status == 3) return '#FA5151';
				return '#000';
			},
			getStatusBgColor(status) {
				if (status == 1) return '#EEFAF6';
				if (status == 2) return '#FFEBE3';
				if (status == 3) return '#FDE8E8';
				return '#000';
			},
			// 获取订单状态
			getStatusName(status) {
				if (status == 1) return '成功';
				if (status == 2) return '处理中';
				if (status == 3) return '失败';
				return '成功';
			},
			getFetchStatusColor(status) {
				if (status == 1) return '#FC926A';
				if (status == 2) return '#6AE8BD';
				return '#000';
			},
			getFetchStatusBgColor(status) {
				if (status == 1) return '#FFEBE3';
				if (status == 2) return '#EEFAF6';
				return '#000';
			},
			// 获取订单状态
			getFetchStatusName(status) {
				if (status == 1) return '处理中';
				if (status == 2) return '已完成';
				return '成功';
			},
			//获取结算状态
			getResultStatus(status) {
				if (status == 0) return '未结算';
				if (status == 1) return '已结算';
				return '未结算';
			},
			toSigleOrderDetail(order) {
				console.log(order)
				uni.navigateTo({
					url: `/pages/order-detail/order-detail?order=${encodeURIComponent(JSON.stringify(order))}&isSigle=true`
				});
			},
			toOrderDetail(order) {
				console.log(order)
				uni.navigateTo({
					url: `/pages/order-detail/order-detail?order=${encodeURIComponent(JSON.stringify(order))}&isSigle=false`
				});
			},
			toCopy(content) {
				uni.setClipboardData({
					data: content
				})
			},
      //审核方法
      async getTypeList() {
        const res = await this.$http({
          method: 'GET',
          url: '/product/type/list',
        });

        if (res) {
          this.typeList = res.data.filter(item => item.name !== '热门回收');

          this.$nextTick(() => {
            this.typeId = this.typeList[0].id;
            this.getCardList();
          })
        }
      },
      switchCardType(index) {
        if (index == this.selectedIndex) return;
        this.selectedIndex = index;
        this.typeId = this.typeList[this.selectedIndex].id;

        this.getCardList();
      },
      async getCardList() {
        const res = await this.$http({
          method: 'GET',
          url: '/product/product/list',
          data: {
            prodTypeId: this.typeId
          }
        });

        if (res) {
          this.cardList = res.data;
        }
      },
      toCardList(item) {
        uni.setStorageSync('selectedItem', JSON.stringify(item));
        uni.navigateTo({
          url: '/pages/shop-detail/shop-detail'
        })
      }
		}
	};
</script>

<style lang="scss" scoped>
	.order-page {
		height: 100vh;
		width: 100vw;
		position: fixed;
		top: 0;
		left: 0;
		background-color: #F7FAFF;
		padding: 26rpx;
		display: flex;
		flex-direction: column;
	}

	// 订单类型切换
	.order-type-switch {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 20rpx;

		.order-type {
			padding: 5px 14px;
			color: rgba(0, 0, 0, 0.60);
			cursor: pointer;
			font-size: 32rpx;
		}

		.order-type.active {
			color: #000;
			font-weight: 700;
			font-size: 32rpx;
		}
	}

	// tab切换
	.tabs {
		display: flex;
		justify-content: space-between;
		margin-bottom: 24rpx;
		padding: 0 80rpx;

		.tab {
			padding-bottom: 20rpx;
			color: rgba(0, 0, 0, 0.45);
			cursor: pointer;
			position: relative;
			display: inline-block;
			font-size: 32rpx;

			&.active {
				color: #4D7EF4;
				font-weight: 700;
			}

			&.active::after {
				content: '';
				position: absolute;
				left: 10%;
				bottom: 0;
				width: 80%;
				height: 8rpx;
				background: #4D7EF4;
				border-radius: 4rpx;
			}
		}
	}

	// 订单列表
	.order-item {
		padding: 30rpx 40rpx;
		margin-bottom: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;

		.order-item-title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 36rpx;

			.order-item-title-left {
				display: flex;
				align-items: center;

				.order-item-title-text {
					color: rgba(0, 0, 0, 0.60);
					font-size: 24rpx;
					margin-right: 6rpx;
				}
			}

			.order-status {
				font-size: 20rpx;
				padding: 6rpx 18rpx;
				margin-right: 10px;
				border-radius: 10rpx;
			}

			.order-info {
				color: rgba(0, 0, 0, 0.60);
				font-size: 24rpx;
			}
		}

		.order-item-content {
			display: flex;
			margin-bottom: 50rpx;

			.order-item-content-image {
				width: 92rpx;
				height: 92rpx;
			}

			.order-item-content-right {
				margin-left: 24rpx;

				.order-item-content-title {
					color: #000;
					font-size: 24rpx;
				}

				.order-item-content-info {
					color: #000;
					font-size: 20rpx;
					margin-top: 8rpx;
				}

				.order-item-content-time {
					margin-top: 16rpx;
					color: rgba(0, 0, 0, 0.40);
					font-size: 24rpx;
				}
			}
		}

		.order-item-result {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 24rpx;
			color: rgba(0, 0, 0, 0.80);
		}

		.order-item-some-result {
			display: flex;
			justify-content: flex-end;
			font-size: 24rpx;
			color: rgba(0, 0, 0, 0.80);
		}
	}

	// 加载更多
	.loading-more,
	.no-more-data {
		text-align: center;
		padding-bottom: 10rpx;
		color: rgba(0, 0, 0, 0.60);
		font-size: 24rpx;
	}

	/deep/ .scroll-view {
		overflow-y: auto;
		-webkit-overflow-scrolling: touch;
	}

  //审核
  .card-scroll-container {
    margin-left: 20rpx;
    white-space: nowrap;
    margin-bottom: 20rpx;
    width: 100%;
    background-color: white;
    box-sizing: border-box;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);

    .type-item {
      display: inline-block;
      padding: 20rpx 5rpx;
      margin-right: 45rpx;
      font-size: 32rpx;
      color: rgba(0, 0, 0, 0.45);
      cursor: pointer;
      border-bottom: 4rpx solid transparent;
      border-radius: 2px;

      &.active {
        color: #4D7EF4;
        font-weight: 700;
        border-bottom-color: #4D7EF4;
      }
    }
  }
</style>